package com.gxnu.edu.cn.client.controller;

import com.gxnu.edu.cn.ttxxt.entity.Messages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.swing.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class MessageClient {
    @Autowired
    private RestTemplate restTemplate;

    private String baseUrl = "http://localhost:8080";



    public CompletableFuture<Messages> sendTextMessage(Map<String, Object> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 添加请求头设置
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

                ResponseEntity<Messages> response = restTemplate.postForEntity(
                        baseUrl + "/api/messages/text",
                        entity,
                        Messages.class
                );

                if (response.getStatusCode().is2xxSuccessful()) {
                    return response.getBody();
                } else if (response.getStatusCode() == HttpStatus.BAD_REQUEST) {
                    // 弹出错误弹窗
                    JOptionPane.showMessageDialog(null, "发送者和接收者的 IP 不在同一内网，消息发送失败", "错误", JOptionPane.ERROR_MESSAGE);
                    throw new RuntimeException("发送者和接收者的 IP 不在同一内网，消息发送失败");
                } else {
                    throw new RuntimeException("发送文本消息失败，状态码: " + response.getStatusCodeValue());
                }
            } catch (HttpStatusCodeException e) {
                if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                    // 弹出错误弹窗
                    JOptionPane.showMessageDialog(null, "发送者和接收者的 IP 不在同一内网，消息发送失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
                throw new RuntimeException("发送文本消息失败，状态码: " +
                        ", 错误信息: " + e.getResponseBodyAsString(), e);
            } catch (Exception e) {
                throw new RuntimeException("发送文本消息失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Messages> sendFileMessage(Map<String, Object> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 添加请求头设置
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

                ResponseEntity<Messages> response = restTemplate.postForEntity(
                        baseUrl + "/api/messages/file",
                        entity,
                        Messages.class
                );

                if (response.getStatusCode().is2xxSuccessful()) {
                    return response.getBody();
                } else {
                    throw new RuntimeException("发送文件消息失败，状态码: " + response.getStatusCodeValue());
                }
            } catch (HttpStatusCodeException e) {
                throw new RuntimeException("发送文件消息失败，状态码: "  +
                        ", 错误信息: " + e.getResponseBodyAsString(), e);
            } catch (Exception e) {
                throw new RuntimeException("发送文件消息失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Messages> sendShakeMessage(Map<String, Object> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Messages> response = restTemplate.postForEntity(
                        baseUrl + "/api/messages/shake",
                        request,
                        Messages.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("发送摇一摇消息失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<List<Messages>> getChatHistory(Long userId, Long contactId, Integer isGroup, int page, int size) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + "/api/messages/history")
                        .queryParam("userId", userId)
                        .queryParam("contactId", contactId)
                        .queryParam("isGroup", isGroup)
                        .queryParam("page", page)
                        .queryParam("size", size);

                ResponseEntity<List<Messages>> response = restTemplate.exchange(
                        builder.toUriString(),
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<Messages>>() {}
                );
                if (response.getStatusCode() == HttpStatus.OK) {
                    return response.getBody();
                } else {
                    throw new RuntimeException("获取聊天记录失败，状态码: " + response.getStatusCodeValue());
                }
            } catch (Exception e) {
//                log.error("获取聊天记录失败: ", e);
                throw new RuntimeException("获取聊天记录失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<List<Messages>> getUnreadMessages(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List> response = restTemplate.getForEntity(
                        baseUrl + "/api/messages/unread",
                        List.class,
                        userId
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取未读消息失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> markMessagesAsRead(Long userId, Long contactId, Integer isGroup) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> request = Map.of(
                        "userId", userId,
                        "contactId", contactId,
                        "isGroup", isGroup
                );
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/messages/mark-read",
                        request,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("标记消息为已读失败: " + e.getMessage(), e);
            }
        });
    }
}